package com.wangsd.web.weixin.controller;


import com.alibaba.fastjson.JSONObject;
import com.wangsd.common.component.WxComponentService;
import com.wangsd.common.entity.Result;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMenuService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.open.api.WxOpenComponentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/api/menu")
public class WechatMenuController {
    @Autowired
    WxComponentService wxComponentService;

    /**
     * 获取公众号菜单
     *
     * @param gzhId 必须是授权后的公众号id
     * @return menu的json
     */
    @RequestMapping("/wxMenu")
    public Object getWxMenu(String gzhId) {
        try {
            WxOpenComponentService wxOpenComponentService = wxComponentService.getWxOpenComponentService();
            WxMpService wxMpService = wxOpenComponentService.getWxMpServiceByAppid(gzhId);

            String API_URL_PREFIX = "https://api.weixin.qq.com/cgi-bin/menu/get";
            String menuStr = wxMpService.get(API_URL_PREFIX, null);
            log.info(menuStr);
            JSONObject jsonObject = JSONObject.parseObject(menuStr);
            return Result.success(jsonObject);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return Result.fail("获取菜单失败");
    }

    /**
     * 保存公众号菜单
     *
     * @param gzhId    必须是授权后的公众号id
     * @param menuJson 修改过后的JSON字符串
     * @return
     */
    @PostMapping("/saveWxMenu")
    @ResponseBody
    public Object saveWxMenu(String gzhId, String menuJson) {
        try {
            WxOpenComponentService wxOpenComponentService = wxComponentService.getWxOpenComponentService();
            WxMpService wxMpService = wxOpenComponentService.getWxMpServiceByAppid(gzhId);
            WxMpMenuService wxMpMenuService = wxMpService.getMenuService();
            String result = wxMpMenuService.menuCreate(menuJson);
            return Result.success(result);
        } catch (WxErrorException e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }
}
